package com.gcloud.mesh.dcs.strategy.huawei;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gcloud.mesh.dcs.annotation.SchedulerLog;
import com.gcloud.mesh.header.exception.BaseException;
import com.huaweicloud.sdk.core.auth.GlobalCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.sms.v3.SmsClient;
import com.huaweicloud.sdk.sms.v3.model.BtrfsFileSystem;
import com.huaweicloud.sdk.sms.v3.model.CreateTaskRequest;
import com.huaweicloud.sdk.sms.v3.model.CreateTaskResponse;
import com.huaweicloud.sdk.sms.v3.model.Disk;
import com.huaweicloud.sdk.sms.v3.model.ListServersResponse;
import com.huaweicloud.sdk.sms.v3.model.PostTask;
import com.huaweicloud.sdk.sms.v3.model.ShowServerResponse;
import com.huaweicloud.sdk.sms.v3.model.SourceServerByTask;
import com.huaweicloud.sdk.sms.v3.model.SourceServersResponseBody;
import com.huaweicloud.sdk.sms.v3.model.TargetDisks;
import com.huaweicloud.sdk.sms.v3.model.TargetServerByTask;
import com.huaweicloud.sdk.sms.v3.model.VolumeGroups;
import com.huaweicloud.sdk.sms.v3.region.SmsRegion;

import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
public class CreateTaskSolution {

//    public static void main(String[] args) {
//    	CreateTaskSolution createTask = new CreateTaskSolution();
//    	createTask.createTask(null, null, "ecs-5fc0", "cn-north-1");
//    }
	@SchedulerLog(stepName="创建迁移任务")
    public String createTask(String jobId, String ak, String sk, String name, String regionId, List<TargetDisks> disk, String sourceServerId) {
      	if(StringUtils.isBlank(ak)) {
     		 ak = "8QVISVT4XJHUNMIEPZBQ";
  	   	}
  	   	if(StringUtils.isBlank(sk)) {
  	   		sk = "GingsSlHInSkQ3x47jMSEjFT0uumSJgplZs926Cw";
  	   	}
  	   	if(StringUtils.isBlank(regionId)) {
  	   	    regionId = "cn-north-1";
  	   	}
  	    HttpConfig config = HttpConfig.getDefaultHttpConfig();
  	    config.withIgnoreSSLVerification(true);
        ICredential auth = new GlobalCredentials()
                .withAk(ak)
                .withSk(sk);

        SmsClient client = SmsClient.newBuilder()
                .withCredential(auth)
                .withHttpConfig(config)
                .withRegion(SmsRegion.valueOf("ap-southeast-1"))
                .build();
        CreateTaskRequest request = new CreateTaskRequest();
        PostTask body = new PostTask();
        List<VolumeGroups> listTargetServerVolumeGroups = new ArrayList<>();
        // List<PhysicalVolumes> listDisksPhysicalVolumes = new ArrayList<>();
        // String sourceServerId = getSourceServerId(ak, sk, name);
        log.debug("源服务器迁移id是"+sourceServerId);
        // System.out.println("源id:"+sourceServerId);
        List<TargetDisks> listTargetServerDisks = disk;
//        		new ArrayList<>();
//        listTargetServerDisks.add(
//            new TargetDisks()
//                .withName("test")
//                .withPhysicalVolumes(listDisksPhysicalVolumes)
//                .withSize(42948624384L)
//                .withUsedSize(2831396864L)
//        );
        List<BtrfsFileSystem> listTargetServerBtrfsList = new ArrayList<>();
        TargetServerByTask targetServerbody = new TargetServerByTask();
        targetServerbody.withName(name);
        targetServerbody.withBtrfsList(listTargetServerBtrfsList)
            .withDisks(listTargetServerDisks)
            .withVolumeGroups(listTargetServerVolumeGroups);
        SourceServerByTask sourceServerbody = new SourceServerByTask();
        sourceServerbody.withId(sourceServerId);
        body.withUsePublicIp(true);
        body.withVmTemplateId(RegionType.getRegionType(regionId).getTemplateId());
        body.withProjectId(RegionType.getRegionType(regionId).getProjectId());
        body.withProjectName(regionId);
        body.withRegionId(regionId);
        body.withRegionName(RegionType.getRegionType(regionId).getRegionName());
        body.withTargetServer(targetServerbody);
        body.withSourceServer(sourceServerbody);
        body.withOsType("LINUX");
        body.withType(PostTask.TypeEnum.fromValue("MIGRATE_FILE"));
        body.withName("mesh_test");
        request.withBody(body);
        String taskId = null;
        try {
            CreateTaskResponse response = client.createTask(request);
            taskId = response.getId();
        } catch (ConnectionException e) {
        	log.error("迁移创建任务连接失败："+ e);
        } catch (RequestTimeoutException e) {
        	log.error("迁移创建任务超时："+ e);
            e.printStackTrace();
        } catch (ServiceResponseException e) {
        	log.error("迁移创建任务异常："+ e.getErrorMsg());
        }
        return taskId;
    }
    
    private Map<String, String> mapNameAndSourceServer(String ak, String sk) {
    	log.debug("映射华为云的迁移源和服务器对应关系");
    	ListServersSolution listServersDetailsSolution = new ListServersSolution();
    	Map<String, String> map = new HashMap<>();
    	ListServersResponse res = listServersDetailsSolution.listServers(ak, sk);
    	List<SourceServersResponseBody>  sourceServers = res.getSourceServers();
    	if(sourceServers != null) {
    		for(SourceServersResponseBody body : sourceServers) {
    			if(body.getCurrentTask() == null) {
    				map.put(body.getName(), body.getId());
    			}
    		}
    	}
    	log.debug("映射华为云的迁移源和服务器对应关系结束，对应关系如下"+map);
    	return map;
    }
    @SchedulerLog(stepName="获取迁移源配置信息")
    public String getSourceServerId(String jobId, String ak, String sk, String name) {
    	Map<String,String> sourceNameMap = mapNameAndSourceServer(ak, sk);
    	String sourceServerId = sourceNameMap.get(name);
    	if(sourceServerId == null) {
    		throw new BaseException(String.format("该服务器%s可能未安装迁移agent，目前获取不到迁移源", name));
    	}
    	return sourceServerId;
    }
    @SchedulerLog(stepName="获取迁移源磁盘信息")
    public List<TargetDisks> getTargetDisk(String jobId, String ak, String sk, String sourceServerId){
    	log.debug("开始获取源服务器磁盘信息");
    	ShowServerSolution showServer = new ShowServerSolution();
    	ShowServerResponse res = showServer.showServer(ak, sk, sourceServerId);
    	List<Disk> disks = res.getDisks();
    	List<TargetDisks> listTargetServerDisks = new ArrayList<>();
    	for(Disk disk : disks) {
            listTargetServerDisks.add(
                    new TargetDisks()
                        .withName(disk.getName())
                        .withPhysicalVolumes(disk.getPhysicalVolumes())
                        .withSize(disk.getSize())
                        .withUsedSize(disk.getUsedSize())
                );
    	}
    	log.debug("获取华为云源服务器信息结束");
    	return listTargetServerDisks;
    }
}